#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "config.h"
#include "errno.h"

#define MAX_BUF		65536
#define MAX_KEY		256
#define MAX_VALUE	4096

char buf[MAX_BUF];
char *free_pt = buf;
char *keys[MAX_KEY], *values[MAX_VALUE];
int value_belongs[MAX_VALUE];
int key_num = 0, value_num = 0;

char *get_str_buf(int size) {
	char *res = free_pt;

	if (free_pt - buf + size > MAX_BUF)
		return 0;
	free_pt += size;
	return res;
}

int config_read(const char *fname) {
	FILE *fin;
	char buf[128];

	fin = fopen(fname, "r");
	if (fin == 0) {
		if (errno == ENOENT)
			return E_FILE_NOT_EXIST;
		return E_CANNOT_OPEN_FILE;
	}
	while (fgets(buf, 128, fin) != 0) {
		char *eq = strchr(buf, '=');

		if (eq != 0) {
			*(eq++) = '\0';
			if (*(eq + strlen(eq) - 1) == '\n')
				*(eq + strlen(eq) - 1) = '\0';
			keys[key_num] = get_str_buf(strlen(buf) + 1);
			values[value_num] = get_str_buf(strlen(eq) + 1);
			strcpy(keys[key_num++], buf);
			strcpy(values[value_num++], eq);
		}
	}
	fclose(fin);
	return 0;
}

int config_create(const char *fname) {
	return -1;
}

int config_count(const char *key) {
	int i, key_id = -1, count = 0;

	for (i = 0; i < key_num; i++)
		if (!strcmp(key, keys[i]))
			key_id = i;
	if (key_id == -1)
		return 0;
	for (i = 0; i < value_num; i++)
		if (value_belongs[i] == key_id)
			count++;
	return count;
}

const char *config_get(const char *key, int index) {
	int i, key_id = -1, count = 0;

	for (i = 0; i < key_num; i++)
		if (!strcmp(key, keys[i]))
			key_id = i;
	if (key_id == -1)
		return 0;
	for (i = 0; i < value_num; i++)
		if (value_belongs[i] == key_id) {
			if (count == index)
				return values[i];
			count++;
		}
	return 0;
}
